<template>
  <el-drawer
    v-model="dialog.visible"
    :title="dialog.title"
    size="80%"
    @close="dialog.visible = false"
  >
    <div class="search-bar">
      <el-form ref="queryFormRef" :inline="true">
        <el-form-item>
          <SearchBar
            :show_checkbox="true"
            :show_original_text="true"
            @onSearch="onSearch"
          ></SearchBar>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="flex-x-between mb-10px">
        <div>
          <!-- 全选按钮（列表模式下显示） -->
          <el-checkbox v-if="!showGrid" v-model="isAllSelected" @change="handleSelectAll">
            全选
          </el-checkbox>
        </div>
        <div>
          <el-button icon="Grid" circle title="表格" @click="handleGrid"></el-button>
          <el-button icon="List" circle title="列表" @click="handleList"></el-button>
        </div>
      </div>

      <!-- 表格模式 -->
      <div v-if="showGrid">
        <ArticleTable
          ref="articleTableRef"
          :listData="pageData"
          :show_checkbox="true"
          :page_index="queryParams.pageNum"
          :page_size="queryParams.pageSize"
          @selection-change="handleSelectionChange"
        ></ArticleTable>
      </div>

      <!-- 列表模式 -->
      <div v-if="!showGrid">
        <ArticleList
          ref="articleListRef"
          :listData="pageData"
          :show_checkbox="true"
          @selection-change="handleSelectionChange"
        ></ArticleList>
      </div>

      <!-- 分页 -->
      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handlePageChange"
      />
    </el-card>

    <!-- 弹窗底部 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确定</el-button>
        <el-button @click="handleCloseDialog">取消</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from "vue";
import ArticleList from "./ArticleList.vue";
import ArticleTable from "./ArticleTable.vue";
import { ArticleQuery } from "./type";
import ArticleAPI, { ArticlePageVO, ArticlePageQuery } from "@/api/project/article";

import TopicArticleAPI, {
  TopicArticlePageVO,
  TopicArticleForm,
  TopicArticlePageQuery,
} from "@/api/project/topic-article";

const loading = ref(false);
const total = ref(0);
const showGrid = ref(true); // 是否显示表格模式
const isAllSelected = ref(false); // 是否全选

// 表格组件的引用
const articleTableRef = ref();
const articleListRef = ref();

// 查询参数
const queryParams = reactive<TopicArticlePageQuery>({
  pageNum: 1,
  pageSize: 10,
  topicId: "0",
  searchWords: "",
  searchType: "0",
  selected: "article",
});

// 文章表格数据
const pageData = ref<ArticlePageVO[]>([]);
const formData = reactive<TopicArticleForm>({});
const topicId = ref(0);
// 弹窗
const dialog = reactive({
  title: "添加",
  visible: false,
});

// 选中的行数据
const selectedRows = ref<ArticlePageVO[]>([]);

// 处理子组件传递的选中行数据
const handleSelectionChange = (selection: any) => {
  selectedRows.value = selection;
  // 更新全选状态
  isAllSelected.value = selectedRows.value.length === pageData.value.length;
};

// 全选/取消全选
const handleSelectAll = (checked: boolean) => {
  if (checked) {
    // 全选
    selectedRows.value = [...pageData.value];
  } else {
    // 取消全选
    selectedRows.value = [];
  }
  // 通知子组件更新选中状态
  if (articleListRef.value) {
    articleListRef.value.setSelection(selectedRows.value);
  }
};

// 提交选中的数据
const handleSubmit = () => {
  const ids = selectedRows.value.map((row) => Number(row.articleId));
  if (!ids) {
    ElMessage.warning("请勾选数据");
    return;
  }

  if (ids) {
    loading.value = true;

    formData.topicId = topicId.value;
    formData.articleIds = ids;

    TopicArticleAPI.add(formData)
      .then(() => {
        ElMessage.success("新增成功");
        handleCloseDialog();
        onQuery();
      })
      .finally(() => (loading.value = false));
  }
};

// 切换表格模式
const handleGrid = () => {
  showGrid.value = true;
};

// 切换列表模式
const handleList = () => {
  showGrid.value = false;
};

// 关闭弹窗
const handleCloseDialog = () => {
  if (articleTableRef.value) {
    articleTableRef.value.clearSelection(); // 清空表格选中状态
  }
  if (articleListRef.value) {
    articleListRef.value.clearSelection(); // 清空列表选中状态
  }
  selectedRows.value = []; // 清空选中的行数据
  isAllSelected.value = false; // 重置全选状态
  dialog.visible = false;
};

// 新增专门处理分页变化的方法
const handlePageChange = () => {
  // 直接使用当前的queryParams进行查询
  loading.value = true;

  TopicArticleAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
};

// 查询文章
const onSearch = (queryAticleParams: ArticleQuery) => {
  // 更新搜索条件
  queryParams.searchWords = queryAticleParams.searchWords;
  queryParams.searchType = queryAticleParams.searchType;

  // 重置页码为1
  queryParams.pageNum = 1;

  if (queryAticleParams.selected) {
    queryParams.selected = "article_notin";
    queryParams.topicId = topicId.value;
  } else {
    queryParams.selected = "article";
    if (queryParams.searchWords === "") {
      ElMessage.warning("请输入检索信息");
      return;
    }
  }

  loading.value = true;

  TopicArticleAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
};

const emit = defineEmits(["onQuery"]);
const onQuery = () => {
  emit("onQuery");
};

// 打开弹窗
const openShowDialog = async (id: string, title: string) => {
  dialog.visible = true;
  dialog.title = "添加" + title;
  topicId.value = Number(id);
};

defineExpose({
  openShowDialog,
});
</script>
